package com.sky.com.sky.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.RandomUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.sky.context.ThreadLocalUtil;
import com.sky.dto.*;
import com.sky.entity.*;
import com.sky.exception.BusinessException;
import com.sky.mapper.*;
import com.sky.result.PageResult;
import com.sky.service.OrderService;
import com.sky.service.ShoppingCartService;
import com.sky.utils.HttpClientUtil;
import com.sky.utils.WeChatPayUtil;
import com.sky.vo.OrderPaymentVO;

import com.sky.vo.OrderStatisticsVO;
import com.sky.vo.OrderSubmitVO;
import com.sky.vo.OrderVO;
import com.sky.websocket.WebSocketServer;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

@RequiredArgsConstructor
@Service
@Slf4j
public class OrderServiceImpl implements OrderService {
    private final OrderMapper orderMapper;


    private final OrderDetailMapper orderDetailMapper;

    private final ShoppingCartService shoppingCartService;
    ;

    private final AddressBookMapper addressBookMapper;

    private final ShoppingCartMapper shoppingCartMapper;


    private final WebSocketServer webSocketServer;


    @Autowired
    WeChatPayUtil weChatPayUtil;

    @Autowired
    UserMapper userMapper;

    @Value("${sky.shop.address}")
    private String shopAddress;

    @Value("${sky.baidu.ak}")
    private String ak;


    @Override
    public PageResult pagesearch(OrdersPageQueryDTO ordersPageQueryDTO) {
        PageHelper.startPage(ordersPageQueryDTO.getPage(), ordersPageQueryDTO.getPageSize());
        //1.查询该参数对应的订单
        List<OrderVO> orderVOList = orderMapper.getList(ordersPageQueryDTO);
        //2.把该订单转为Page对象
        Page<OrderVO> page = (Page<OrderVO>) orderVOList;
        StringBuilder sb = new StringBuilder();
        for (OrderVO orderVO : page) {
            //3.根据订单id查询订单具体信息
            List<OrderDetail> byOrderId = orderDetailMapper.getByOrderId(orderVO.getId());
            byOrderId.forEach(Dish -> {
                sb.append(Dish.getName()).append("*").append(Dish.getNumber()).append(",");
            });
            String str = sb.toString().toString();
            orderVO.setOrderDishes(sb.deleteCharAt(str.length() - 1).toString());
        }

        return new PageResult(page.getTotal(), page.getResult());
    }

    /**
     * 下单
     *
     * @param ordersSubmitDTO
     * @return
     **/
    @Override
    @Transactional
    public OrderSubmitVO submit(OrdersSubmitDTO ordersSubmitDTO) {
        //1. 查询收货地址信息
        AddressBook addressBook = addressBookMapper.getById(ordersSubmitDTO.getAddressBookId());
        if (addressBook == null) {
            throw new BusinessException(200, "请选择正确收货地址下单!");
        }
        //检查用户的收货地址是否超出配送范围
        checkOutOfRange(addressBook.getCityName()+addressBook.getDistrictName()+addressBook.getDetail());

        //2. dto->entity
        Orders orders = BeanUtil.copyProperties(ordersSubmitDTO, Orders.class);
        //补充信息
        orders.setNumber(RandomUtil.randomNumbers(8)); //订单号
        orders.setStatus(Orders.PENDING_PAYMENT); //订单状态 1 待付款
        orders.setUserId(ThreadLocalUtil.getCurrentId()); //下单用户
        orders.setOrderTime(LocalDateTime.now()); //下单时间
        orders.setPayStatus(Orders.UN_PAID); //支付状态 0 未支付
        orders.setPhone(addressBook.getPhone());//手机号
        orders.setAddress(addressBook.getCityName() + addressBook.getDistrictName() + addressBook.getDetail());//地址信息
        orders.setConsignee(addressBook.getConsignee());//收货人
        //3. 保存订单
        orderMapper.insert(orders);
        //4. 查询购物车列表，遍历
        List<ShoppingCart> cartList = shoppingCartService.getList();
        if (CollUtil.isEmpty(cartList)) {
            throw new BusinessException(200, "请选择菜品后进行下单");
        }
        for (ShoppingCart shoppingCart : cartList) {
            // 4-1 购物项转订单明细
            OrderDetail orderDetail = BeanUtil.copyProperties(shoppingCart, OrderDetail.class, "id");
            //4-2 订单明细设置订单id
            orderDetail.setOrderId(orders.getId());
            //4-3 保存订单明细
            orderDetailMapper.insert(orderDetail);
        }
        //4-4 清空购物车
        shoppingCartService.clean();
        //5. 组装并返回vo
        OrderSubmitVO orderSubmitVO = OrderSubmitVO.builder()
                .id(orders.getId())
                .orderAmount(orders.getAmount())
                .orderNumber(orders.getNumber())
                .orderTime(orders.getOrderTime())
                .build();
        return orderSubmitVO;
    }

   /*
   *  检查客户的收货地址是否超出配送范围
   * @param address
   * */
    private void checkOutOfRange(String address){
        HashMap<String, String> map = new HashMap<>();
        map.put("address",shopAddress);
        map.put("output","json");
        map.put("ak",ak);

        //获取店铺的经纬度坐标
        String shopCoordinate = HttpClientUtil.doGet("https://api.map.baidu.com/geocoding/v3", map);

        JSONObject jsonObject = JSON.parseObject(shopCoordinate);
        if(!jsonObject.getString("status").equals("0")){
            throw new BusinessException(200,"店铺解析地址失败");
        }
        //数据解析
        JSONObject location = jsonObject.getJSONObject("result").getJSONObject("location");
        String lat = location.getString("lat");
        String lng = location.getString("lng");
        //店铺经纬度坐标
        String shopLngLat = lat + "," + lng;
        map.put("address",address);
        //获取用户收获地址的经纬度坐标
        String userCoordinate = HttpClientUtil.doGet("https://api.map.baidu.com/geocoding/v3", map);

        jsonObject = JSON.parseObject(userCoordinate);
        if(!jsonObject.getString("status").equals("0")){
            throw new BusinessException(200,"收获地址解析失败");
        }
        //数据解析
        location = jsonObject.getJSONObject("result").getJSONObject("location");
        lat = location.getString("lat");
        lng = location.getString("lng");
        //用户收货地址经纬度坐标
        String userLngLat=lat+","+lng;

        map.put("origin",shopLngLat);
        map.put("destination",userLngLat);

        //路线规划
        String json = HttpClientUtil.doGet("https://api.map.baidu.com/directionlite/v1/driving", map);

        jsonObject = JSON.parseObject(json);
        if(!jsonObject.getString("status").equals("0")){
            throw new BusinessException(200,"配送路线规划失败!");
        }
        //数据解析
        JSONObject result = jsonObject.getJSONObject("result");
        JSONArray jsonArray = (JSONArray) result.get("rotes");
        Integer distance = (Integer) ((JSONObject) jsonArray.get(0)).get("distance");
        if(distance>5000){
            //配送距离超过5000米
            throw new BusinessException(200,"超出配送范围");
        }
    }


    /**
     * 订单支付
     *
     * @param ordersPaymentDTO
     * @return
     **/
    @Override
    public OrderPaymentVO payment(OrdersPaymentDTO ordersPaymentDTO) throws Exception {
        // 当前登录用户id
        Long userId = ThreadLocalUtil.getCurrentId();
        User user = userMapper.getById(userId);

        //调用微信支付接口，生成预支付交易单
        JSONObject jsonObject = weChatPayUtil.pay(
                ordersPaymentDTO.getOrderNumber(),//商户订单号
                new BigDecimal(0.01), //支付金额，单位:元
                "苍穹外卖订单",//商品描述
                user.getOpenid()//微信用户的opendi
        );
        if (jsonObject.getString("code") != null && jsonObject.getString("code").equals("ORDERPAID")) {
            throw new BusinessException(200, "该订单已支付");
        }
        OrderPaymentVO vo = jsonObject.toJavaObject(OrderPaymentVO.class);
        vo.setPackageStr(jsonObject.getString("package"));
        return vo;
    }


    /**
     * 支付成功，修改订单状态
     *
     * @param outTradeNo
     **/
    @Override
    public void paySucess(String outTradeNo) {
        // 根据订单号擦汗寻当前用户的订单
        Orders ordersDB = orderMapper.getByNumber(outTradeNo);

        //根据订单id更新订单的状态，支付方式、支付状态、结账时间
        Orders orders = Orders.builder()
                .id(ordersDB.getId())
                .status(Orders.TO_BE_CONFIRMED)
                .payStatus(Orders.PAID)
                .checkoutTime(LocalDateTime.now())
                .build();
        orderMapper.update(orders);
        //--------webSocket 发送消息给客户端---------
        HashMap<String, Object> map = new HashMap<>();
        map.put("type",1);//消息类型 1表示来单提醒
        map.put("orderId",orders.getId());
        map.put("content","订单号"+outTradeNo);

        //通过webSocket实现来单提醒，向客户端浏览器推送消息
        webSocketServer.sendToAllClient(JSON.toJSONString(map));
    }

    /**
     * 用户端订单分页查询
     *
     * @param pageNum
     * @param pageSize
     * @param status
     * @return
     **/
    @Override
    public PageResult pageQuery4User(Integer pageNum, Integer pageSize, Integer status) {
        //设置分页
        PageHelper.startPage(pageNum, pageSize);
        //查询条件
        OrdersPageQueryDTO ordersPageQueryDTO = OrdersPageQueryDTO.builder()
                .userId(ThreadLocalUtil.getCurrentId())
                .status(status)
                .build();

        //分页条件查询
        List<Orders> orderList = orderMapper.pageQuery(ordersPageQueryDTO);
        //封装分页
        PageInfo<Orders> pageInfo = new PageInfo<>(orderList);
        List<Orders> list = pageInfo.getList();
        //转VO集合
        List<OrderVO> orderVOList = BeanUtil.copyToList(list, OrderVO.class);
        //查询出订单明细，并疯转入OrderVO进行响应
        if (orderVOList != null && orderVOList.size() > 0) {
            for (OrderVO vo : orderVOList) {
                Long orderId = vo.getId();//订单id
                //查询订单明细
                List<OrderDetail> orderDetails = orderDetailMapper.getByOrderId(orderId);
                //封装OrderVO
                vo.setOrderDetailList(orderDetails);
            }
        }
        return new PageResult(pageInfo.getTotal(), orderVOList);
    }

    /**
     * 订单搜索
     *
     * @param ordersPageQueryDTO
     * @return
     */
    @Override
    public PageResult conditionSearch(OrdersPageQueryDTO ordersPageQueryDTO) {
        //1. 开启分页
        PageHelper.startPage(ordersPageQueryDTO.getPage(), ordersPageQueryDTO.getPageSize());
        //2. 查询
        List<OrderVO> voList = orderMapper.getList(ordersPageQueryDTO);
        //3. 封装分页结果
        Page<OrderVO> page = (Page<OrderVO>) voList;
        //遍历voList,拼接字符串 菜品*数量 ；设置给orderDishes属性
        voList.forEach(orderVO -> {
            //查询订单明细
            List<OrderDetail> detailList = orderDetailMapper.getByOrderId(orderVO.getId());
            //字符串拼接
            StringBuilder builder = new StringBuilder();
            detailList.forEach(orderDetail -> {
                //拼接每个订单明细字符串: 烤鱼*1;米饭*2
                builder.append(orderDetail.getName() + "*" + orderDetail.getNumber() + ";");
            });
            //给orderVO属性赋值
            orderVO.setOrderDishes(builder.toString());
        });
        return new PageResult(page.getTotal(), voList);
    }

    private List<OrderVO> getOrderVOList(PageInfo<Orders> page) {
        //订单列表
        List<Orders> ordersList = page.getList();
        //转为orderVO，包含前端需要的属性orderDishes
        List<OrderVO> voList = BeanUtil.copyToList(ordersList, OrderVO.class);
        //遍历voList,拼接字符串 菜品*数量;设置orderDishes属性
        setOrderDishes(voList);

        return voList;

    }

    private void setOrderDishes(List<OrderVO> voList) {
        voList.stream().map(orderVO -> {
            //查询订单明细
            List<OrderDetail> detailList = orderDetailMapper.getByOrderId(orderVO.getId());
            if (detailList == null || detailList.size() < 1) {
                return null;
            }
            //字符串拼接
            StringBuilder builder = new StringBuilder();
            for (OrderDetail orderDetail : detailList) {
                //拼接每个订单名字字符串:烤鱼*1；米饭*2
                builder.append(orderDetail.getName() + "*" + orderDetail.getName() + ";");
            }
            //给orderVO属性赋值
            orderVO.setOrderDishes(builder.substring(0, builder.length() - 2));
            return orderVO;
        }).collect(Collectors.toList());
    }


    // 历史订单
    @Override
    public PageResult historyOrders(OrdersPageQueryDTO ordersPageQueryDTO) {
        //1. dto 补充用户id
        ordersPageQueryDTO.setUserId(ThreadLocalUtil.getCurrentId());
        //2. 开启分页
        PageHelper.startPage(ordersPageQueryDTO.getPage(), ordersPageQueryDTO.getPageSize());
        //3. 条件查询
        List<OrderVO> voList = orderMapper.getList(ordersPageQueryDTO);
        Page<OrderVO> page = (Page<OrderVO>) voList;
        //4。遍历voList
        for (OrderVO orderVO : voList) {
            //4-1 根据订单id查询明细列表
            List<OrderDetail> detailList = orderDetailMapper.getByOrderId(orderVO.getId());
            // 4-2 设置到vo
            orderVO.setOrderDetailList(detailList);
        }
        //5. 返回分页对象
        return new PageResult(page.getTotal(), voList);
    }

    /**
     * 查询订单详情
     *
     * @param id
     * @return
     **/
    @Override
    public OrderVO orderDetail(Long id) {
        //1. 先查订单
        Orders orders = orderMapper.getById(id);
        //2. 在查明细
        List<OrderDetail> detailList = orderDetailMapper.getByOrderId(id);
        //3. 封装vo
        OrderVO orderVO = BeanUtil.copyProperties(orders, OrderVO.class);
        orderVO.setOrderDetailList(detailList);
        return orderVO;
    }

    /**
     * 用户取消订单
     *
     * @param id
     **/
    @Override
    public void userOrderCancel(Long id) {
        //1. 先查询订单信息
        Orders ordersDB = orderMapper.getById(id);
        //2. 校验订单状态
        if (ordersDB.getStatus() > 2) {
            throw new BusinessException(200, "请联系商家取消订单");
        }
        //3. 判断是否付款(学生不写)
        if (ordersDB.getPayStatus().equals(Orders.TO_BE_CONFIRMED)) {
            try {
                //微信退款
                weChatPayUtil.refund(ordersDB.getNumber(), ordersDB.getNumber(), new BigDecimal("0.01"), new BigDecimal("0.01"));
                // 支付改为已退款
                ordersDB.setPayStatus(Orders.REFUND);
            } catch (Exception e) {
                throw new BusinessException(200, "微信退款失败:" + ordersDB.getNumber());
            }
        }
        //4. 构建取消实体
        Orders orders = Orders.builder()
                .id(ordersDB.getId())
                .status(Orders.CANCELLED)
                .cancelReason("用户取消订单")
                .cancelTime(LocalDateTime.now())
                .build();
        //5. 调用mapper修改订单信息
        orderMapper.update(orders);

    }

    /**
     * 在来一单
     *
     * @param id
     **/
    @Override
    public void repetition(Long id) {
        //1. 查询明细列表
        List<OrderDetail> detailList = orderDetailMapper.getByOrderId(id);
        //清空购物车
        shoppingCartService.clean();
        //2.遍历明细列表
        detailList.forEach(orderDetail -> {
            //2-1 明细封装购物项
            ShoppingCart shoppingCart = BeanUtil.copyProperties(orderDetail, ShoppingCart.class, "id");
            //2-2 补充信息
            shoppingCart.setUserId(ThreadLocalUtil.getCurrentId());
            shoppingCart.setCreateTime(LocalDateTime.now());
            //2-3 添加到数据库
            shoppingCartMapper.insert(shoppingCart);
        });
    }

    /**
     * 各个状态的订单的数量统计
     *
     * @return
     **/
    @Override
    public OrderStatisticsVO statistics() {
        // 根据状态,分别查出待接单、待派送、派送中的订单数量
        Integer toBeConfirmed = orderMapper.countStatus(Orders.TO_BE_CONFIRMED);
        Integer confirmed = orderMapper.countStatus(Orders.CONFIRMED);
        Integer deliveryInProgress = orderMapper.countStatus(Orders.DELIVERY_IN_PROGRESS);

        //将查询出的数据封装到orderStatisticsVO响应
        OrderStatisticsVO statisticsVO = OrderStatisticsVO.builder()
                .toBeConfirmed(toBeConfirmed)
                .confirmed(confirmed)
                .deliveryInProgress(deliveryInProgress)
                .build();
        return statisticsVO;
    }


    @Override
    public OrderVO getdetail(Long id) {
        Orders ordersDB = orderMapper.getById(id);
        OrderVO orderVO = BeanUtil.copyProperties(ordersDB, OrderVO.class);
        List<OrderDetail> orderDetails = orderDetailMapper.getByOrderId(ordersDB.getId());
        orderVO.setOrderDetailList(orderDetails);
        return orderVO;
    }

    /**
     * 接单
     *
     * @param ordersConfirmDTO
     **/
    @Override
    public void confirm(OrdersConfirmDTO ordersConfirmDTO) {
        Orders orders = Orders.builder()
                .id(ordersConfirmDTO.getId())
                .status(Orders.CONFIRMED)
                .build();
        orderMapper.update(orders);
    }

    /**
     * 拒单
     *
     * @param ordersRejectionDTO
     **/
    @Override
    public void rejection(OrdersRejectionDTO ordersRejectionDTO) {
        // 根据id查询订单
        Orders ordersDB = orderMapper.getById(ordersRejectionDTO.getId());
        // 订单只有存在且状态为2 (待接单)才可以拒单
        if (ordersDB == null || !ordersDB.getStatus().equals(Orders.TO_BE_CONFIRMED)) {
            throw new BusinessException(200, "订单状态错误");
        }
        //支付状态
        Integer payStatus = ordersDB.getPayStatus();
        if (payStatus == Orders.PAID) {
            try {
                //用户已支付，需要退款
                weChatPayUtil.refund(
                        ordersDB.getNumber(),
                        ordersDB.getNumber(),
                        new BigDecimal(0.01),
                        new BigDecimal(0.01));
            } catch (Exception e) {
                {
                    throw new BusinessException(200, "退款异常");
                }
            }
            //拒单需要退款，根据订单id更新订单状态、拒单原因、取消时间
            Orders orders = Orders.builder()
                    .id(ordersDB.getId())
                    .status(Orders.CANCELLED)
                    .rejectionReason(ordersRejectionDTO.getRejectionReason())
                    .cancelTime(LocalDateTime.now())
                    .build();
            orderMapper.update(orders);
        }
    }

    /**
     * 取消订单
     *
     * @param ordersCancelDTO
     **/
    @Override
    public void cancel(OrdersCancelDTO ordersCancelDTO) {
        // 根据id查询订单
        Orders ordersDB = orderMapper.getById(ordersCancelDTO.getId());

        //支付状态
        Integer payStatus = ordersDB.getPayStatus();
        if (payStatus == Orders.PAID) {
            try {
                //用户已支付，需要退款
                weChatPayUtil.refund(
                        ordersDB.getNumber(),
                        ordersDB.getNumber(),
                        new BigDecimal(0.01),
                        new BigDecimal(0.01));
            } catch (Exception e) {
                throw new BusinessException(200, "退款异常");
            }
        }
        //管理端取消订单需要退款，根据订单id更新订单状态、取消原因、取消时间
        Orders orders = Orders.builder()
                .id(ordersDB.getId())
                .status(Orders.CANCELLED)
                .rejectionReason(ordersCancelDTO.getCancelReason())
                .cancelTime(LocalDateTime.now())
                .build();
        orderMapper.update(orders);
    }




    /**
     * 派送订单
     *
     * @param orderId
     **/
    @Override
    public void delivery(Long orderId) {
        //根据id查询订单
        Orders ordersDB = orderMapper.getById(orderId);
        //校验订单是否存在，并且状态为已接单
        if(ordersDB == null || ordersDB.getStatus().equals(Orders.CONFIRMED)){
            throw new BusinessException(200,"订单状态错误");
        }
        //更新订单状态，状态为派送中
        Orders orders = Orders.builder()
                .id(ordersDB.getId())
                .status(Orders.DELIVERY_IN_PROGRESS)
                .build();
        orderMapper.update(orders);
    }

    /**
     * 完成订单
     *
     * @param orderId
     **/
    @Override
    public void complete(Long orderId) {
        // 根据id查询订单
        Orders ordersDB = orderMapper.getById(orderId);

        //校验订单是否存在，并且状态为4
        if(ordersDB == null || !ordersDB.getStatus().equals(Orders.DELIVERY_IN_PROGRESS)){
            throw new BusinessException(200,"订单状态错误");
        }
        //更新订单状态为完成，订单完成时间为当前时间
        Orders orders = Orders.builder()
                .id(ordersDB.getId())
                .status(Orders.COMPLETED)
                .deliveryTime(LocalDateTime.now())
                .build();
        orderMapper.update(orders);
    }

    /**
     * 用户催单
     *
     * @param id
     **/
    @Override
    public void reminder(Long id) {
       // 查询订单是否存在
        Orders orders = orderMapper.getById(id);
        if(orders == null){
            throw new BusinessException(200,"订单不存在");
        }
        //基于WebSocket实现催单
        HashMap<String, Object> map = new HashMap<>();
        map.put("type",2);
        map.put("orderId",id);
        map.put("content","订单号: "+orders.getNumber());
        webSocketServer.sendToAllClient(JSON.toJSONString(map));
    }


}
